package com.heima.wemedia.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.apis.article.ArticleClient;
import com.heima.common.constant.WemediaConstants;
import com.heima.common.constant.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocal;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl  extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    WmNewsAutoScanService wmNewsAutoScanService;

    @Autowired
    ArticleClient articleClient;

    @Autowired
    WmNewsTaskService wmNewsTaskService;

    @Autowired
    WmNewsMapper wmNewsMapper;

    /**
     * 初始界面的分页查询
     * @param dto
     * @return
     */
    public ResponseResult findAll(WmNewsPageReqDto dto){
        //1 检查参数
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        //2 对条件进行查询
        IPage<WmNews> page = new Page(dto.getPage(),dto.getSize());

        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();

        // 对状态精确查询
        if(dto.getStatus() != null){
            wrapper.eq(WmNews::getStatus,dto.getStatus());
        }

        // 对频道精确查询
        if(dto.getChannelId() != null){
            wrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }

        // 对时间进行范围查询
        if(dto.getBeginPubDate() != null && dto.getEndPubDate() != null){
            wrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }

        // 对关键字进行模糊查询
        if(dto.getKeyword() != null){
            wrapper.like(WmNews::getTitle,dto.getKeyword());
        }

        // 对用户id进行精确查询
        wrapper.eq(WmNews::getUserId, WmThreadLocal.get().getId());

        wrapper.orderByDesc(WmNews::getPublishTime);

        page = page(page,wrapper);

        log.info("查询到结果,查询到的条数为: {}",page.getTotal());
        log.info("当前用户的id: {}",WmThreadLocal.get().getId());
        //3 返回结果
        ResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        pageResponseResult.setData(page.getRecords());
        return pageResponseResult;

    }


    /**
     * 发布文章
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submit(WmNewsDto dto){
        //1 检验参数
        if(dto == null || dto.getContent() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 将文章传入的参数转换为数据库中的参数 保存或修改
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);

        log.info("已经完成发布文章的基础保存");
        //封面图片  list---> string
        if(dto.getImages() != null && dto.getImages().size() > 0){
            String imageStr = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(imageStr);
        }
        // 当前封面类型为自动时,先保存为null
        if(dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            wmNews.setType(null);
        }
        saveOrUpdateWmNews(wmNews);

        //3 是否为草稿,如果是草稿的话就直接返回
        if(wmNews.getStatus().equals(WmNews.Status.NORMAL.getCode())){
            log.info("文章为草稿");
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        log.info("文章不是草稿");

        //4.不是草稿，保存文章内容图片与素材的关系
        //获取到文章内容中的图片信息
        List<String> materials =  ectractUrlInfo(dto.getContent());
        saveRelativeInfoForContent(materials,wmNews.getId());
        log.info("已经完成文章内容的保存");


        //4.不是草稿，保存文章封面图片与素材的关系，如果当前布局是自动，需要匹配封面图片
        saveRelativeInfoForCover(dto,wmNews,materials);
        log.info("已经完成文章封面的保存");

        /*// 对文章进行自动审核操作
        wmNewsAutoScanService.autoScanWmNews(wmNews.getId());*/

        // 加入到队列中
        wmNewsTaskService.addNewsToTask(wmNews.getId(),wmNews.getPublishTime());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     *
     * @param dto
     * @param wmNews
     * @param materials
     */
    public void saveRelativeInfoForCover(WmNewsDto dto,WmNews wmNews,List<String>materials){
        List<String> images = dto.getImages();

        // 当为自动识别时
        if(dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            // 多图
            if(materials.size()>=3){
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = materials.stream().limit(3).collect(Collectors.toList());
            }
            // 单图
            else if(materials.size()<3 && materials.size()>=1){
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = materials.stream().limit(1).collect(Collectors.toList());
            }
            // 无图
            else{
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }

            if(images!=null && images.size()>0){
                wmNews.setImages(StringUtils.join(images,","));
            }
            updateById(wmNews);

        }

        if(images != null && images.size() > 0){
            saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_COVER_REFERENCE);
        }




    }


    /**
     * 保存图片信息
     * @param materials
     * @param newsId
     */
    public void saveRelativeInfoForContent(List<String> materials,Integer newsId){
        // 保存内容图片信息
        saveRelativeInfo(materials,newsId,WemediaConstants.WM_CONTENT_REFERENCE);
    }


    /**
     * 保存文章图片与素材的关系到数据库中
     * @param materials
     * @param newsId
     * @param type
     */
    private void saveRelativeInfo(List<String> materials, Integer newsId, Short type) {
        // 当为自动识别时
        if(materials!=null && !materials.isEmpty()){
            // 获取到对应的关系数据
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
                    .in(WmMaterial::getUrl, materials));

            // 获取不到关联信息时
            if(wmMaterials == null || wmMaterials.isEmpty()){
                //手动抛出异常   第一个功能：能够提示调用者素材失效了，第二个功能，进行数据的回滚
                throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
            }

            if(materials.size()!=wmMaterials.size()){
                throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
            }

            List<Integer> idList = wmMaterials.stream()
                    .map(WmMaterial::getId)
                    .collect(Collectors.toList());

            wmNewsMaterialMapper.saveRelations(idList,newsId,type);


        }
    }

    /**
     * 获取到文章内容的图片信息
     * @param content
     * @return
     */
    public List<String> ectractUrlInfo(String content){
        List<String> materials = new ArrayList<>();

        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if(map.get("type").equals("image")){
                materials.add((String)map.get("value"));
            }
        }

        return materials;
    }



    /**
     * 保存或更新文章数据
     */
    public void saveOrUpdateWmNews(WmNews wmNews){
        if(wmNews == null){
            return;
        }
        wmNews.setUserId(WmThreadLocal.get().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short)1); // 默认为上架文章
        if(wmNews.getId() == null){
            // 保存文章
            save(wmNews);
        }else{
            // 先删除原来的关联关系,然后保存
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            updateById(wmNews);
        }
    }


    @Autowired
    KafkaTemplate<String, Object> kafkaTemplate;

    /**
     * 上架或下架文章
     * @param dto
     * @return
     */
    public ResponseResult downOrUp(WmNewsDto dto){
        // 检验参数
        if(dto == null){
            log.error("上架文章参数出错");
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 是否可以查询到数据
        WmNews wmNews = wmNewsMapper.selectOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, dto.getId()));
        if(wmNews == null){
            log.error("上架文章数据不存在");
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        // 数据是否是已经发布的状态
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            log.error("上架文章不能上下架操作");
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"当前文章不处于发布状态,无法上下架");
        }

        // 进行数据库信息修改
        if(wmNews.getEnable()!=null && wmNews.getEnable()>-1 && wmNews.getEnable()<2){

            // 修改具体信息
            wmNews.setEnable(dto.getEnable());
            wmNewsMapper.updateById(wmNews);
            log.info("成功修改自媒体端的文章上下架");

            if(wmNews.getArticleId()!=null){
                // 需要将具体的信息发送到kafka中
                Map<String,Object> map = new HashMap<>();
                map.put("articleId",wmNews.getArticleId());
                map.put("enable",dto.getEnable());
                kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(map));
            }

            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"获取到的enable参数出错");


    }


}
